<?php

namespace App\Jobs;

use App\Models\BookCatalog;
use App\Models\BookTitle;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;


class ChunkTable2 implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected  $partCompanyId;
    protected  $projectClassifyId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($partCompanyId, $projectClassifyId)
    {
        $this->partCompanyId = $partCompanyId;
        $this->projectClassifyId = $projectClassifyId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $partCompanyId = $this->partCompanyId;
        $projectClassifyId = $this->projectClassifyId;

        DB::table("book_titles_{$partCompanyId}")
            ->where('project_classify_id',  $this->projectClassifyId)
            ->whereNull('deleted_at')
            ->orderBy('id')
            ->chunkById(100, function ($list) use ($partCompanyId,  $projectClassifyId) {
                $bookTitleIns = $this->getBookTitleInstance($this->partCompanyId,  $this->projectClassifyId);
                foreach ($list as $val) { //往案卷分数据
                    $bookTitleId = $bookTitleIns->insertGetId([
                        'serial_no'           => $val->serial_no,
                        'problem'             => $val->problem,
                        'company_id'          => $val->company_id,
                        'status'              => $val->status,
                        'archives_no'         => $val->archives_no,
                        'project_classify_id' => $val->project_classify_id,
                        'part_company_id'     => $val->part_company_id,
                        'title'               => $val->title,
                        'base_map'            => $val->base_map,
                        'blueprint'           => $val->blueprint,
                        'word_material'       => $val->word_material,
                        'page_num'            => $val->page_num,
                        'store_period'        => $val->store_period,
                        'remark'              => $val->remark,
                        'cabin_no'            => $val->cabin_no,
                        'construction_miles'  => $val->construction_miles,
                        'completed_miles'     => $val->completed_miles,
                        'volume'              => $val->volume,
                        'years'               => $val->years,
                        'secret_level'        => $val->secret_level,
                        'start_date'          => $val->start_date,
                        'end_date'            => $val->end_date,
                        'is_have_data'        => $val->is_have_data,
                        'creator_id'          => $val->creator_id,
                        'created_at'          => $val->created_at,
                        'updated_at'          => $val->updated_at,
                    ]);
                    $getBookCatalogIns = $this->getBookCatalogInstance($partCompanyId, $projectClassifyId);
                    $list2 = DB::table("book_catalogs_{$partCompanyId}")
                        ->leftJoin("book_contents_{$partCompanyId}", "book_contents_{$partCompanyId}.book_catalog_id", "=", "book_catalogs_{$partCompanyId}.id")
                        ->where('book_title_id', $val->id)
                        ->whereNull('deleted_at')
                        ->orderBy('id')
                        ->select("book_catalogs_{$partCompanyId}.*", "book_contents_{$partCompanyId}.file_url")
                        ->orderBy('serial_no')
                        ->get();
                    //往卷内分数据
                    $batchArr = [];
                    foreach ($list2 as $key2 => $val2) {
                        $batchArr[$key2]['serial_no']     = $val2->serial_no;
                        $batchArr[$key2]['book_title_id'] = $bookTitleId;
                        $batchArr[$key2]['title']         = $val2->title;
                        $batchArr[$key2]['file_number']   = $val2->file_number;
                        $batchArr[$key2]['director']      = $val2->director;
                        $batchArr[$key2]['c_date']        = $val2->c_date;
                        $batchArr[$key2]['page_num']      = $val2->page_num;
                        $batchArr[$key2]['file_url']      = $val2->file_url ?: '';
                        $batchArr[$key2]['is_pic']        = $val2->is_pic;
                        $batchArr[$key2]['problem']       = $val2->problem;
                        $batchArr[$key2]['creator_id']    = $val2->creator_id;
                        $batchArr[$key2]['remark']        = $val2->remark;
                        $batchArr[$key2]['created_at']    = $val2->created_at;
                        $batchArr[$key2]['updated_at']    = $val2->updated_at;
                    }
                    if (!empty($batchArr)) {
                        $getBookCatalogIns->insert($batchArr);
                    }
                }
            });
    }

    /**
     * 获取【案卷】数据表实例
     */
    public function getBookTitleInstance($partCompanyId, $projectClassifyId)
    {
        $bookTitleTable   = "book_titles_{$partCompanyId}_{$projectClassifyId}";
        $bookCatalogTable = "book_catalogs_{$partCompanyId}_{$projectClassifyId}";

        if (!Schema::hasTable($bookTitleTable)) {
            DB::update("create table if not exists {$bookTitleTable}   like book_titles");
        }
        if (!Schema::hasTable($bookCatalogTable)) {
            DB::update("create table if not exists {$bookCatalogTable} like book_catalogs");
        }

        $bookTitle = new BookTitle();

        return $bookTitle->setTable($bookTitleTable);
    }

    /**
     * 获取【卷内】表实例
     */
    public function getBookCatalogInstance($partCompanyId, $projectClassifyId)
    {
        $bookCatalogTable = "book_catalogs_{$partCompanyId}_{$projectClassifyId}";

        $bookCatalog = new BookCatalog();

        return $bookCatalog->setTable($bookCatalogTable);
    }


}
